package server.process;

import server.HttpServlet;
import server.Mapper.ContextMapper;
import server.Mapper.HostMapper;
import server.Mapper.WrapperMapper;
import server.Response;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;
import java.util.Objects;

public class RequestMapperProcessor extends Thread {

    private Socket socket;
    private HostMapper hostMapper;

    public RequestMapperProcessor(Socket socket, HostMapper hostMapper) {
        this.socket = socket;
        this.hostMapper = hostMapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            RequestMapper request = new RequestMapper(inputStream);
            Response response = new Response(socket.getOutputStream());
            Map<String, ContextMapper> hostMapper = this.hostMapper.getHostMapper();
            // 静态资源处理
            if(!hostMapper.containsKey(request.getHost())) {
                response.outputHtml(request.getUrl());
            }else{
                ContextMapper contextMapper = hostMapper.get(request.getHost());
                Map<String, WrapperMapper> wrapperMapperMap = contextMapper.getContextMapper();
                if(wrapperMapperMap.containsKey(request.getProject())){
                    WrapperMapper wrapperMapper = wrapperMapperMap.get(request.getProject());
                    Map<String, HttpServlet> servletMap = wrapperMapper.getStringHttpServletMap();
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get("/" + request.getUrl());
                    if(Objects.isNull(httpServlet)){
                        response.outputHtml(request.getUrl());
                    }
                    System.out.println(httpServlet.toString());
                    httpServlet.service(request,response);
                }else {
                    response.outputHtml(request.getUrl());
                }
            }
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
